<template>
    <div class="container-content">
        <div class="container-content-title">{{ $t('platform.setting.config.title') }}
            <el-button type="text" class="p-0" @click="dialogUpdate" v-if="dataStatus == 'dle'">{{ $t('action.edit') }}</el-button>
        </div>
        <component-page-loading :status="dataStatus" v-if="['loading', 'error'].indexOf(dataStatus) >= 0" @reload="getData"></component-page-loading>
        <el-form label-width="180px" class="detail" v-else>
            <el-row>
                <el-col :xl="12">
                    <el-form-item :label="$t('platform.setting.config.payment')">
                        <el-tag effect="plain" size="mini" type="info" v-if="data.payment != null">
                            {{ $t('platform.setting.config.paymentList')[data.payment].label }}
                        </el-tag>
                        <component-page-loading status="nodata" v-else></component-page-loading>
                    </el-form-item>
                </el-col>
                <el-col :xl="12">
                    <el-form-item :label="$t('platform.setting.config.rate')">
                        <el-tag effect="plain" size="mini" type="info" v-if="data.rate != null">
                            <component-page-numeral :num="data.rate" format="0.[00]%"></component-page-numeral>
                        </el-tag>
                        <component-page-loading status="nodata" v-else></component-page-loading>
                    </el-form-item>
                </el-col>
                <el-col :xl="12">
                    <el-form-item :label="$t('platform.setting.config.currency')">
                        <el-tag v-for="(code,index) in data.currency" :key="index" effect="plain" size="mini" type="info" class="mr-1">{{ code }}</el-tag>
                        <component-page-loading status="nodata" v-if="!data.currency.length"></component-page-loading>
                    </el-form-item>
                </el-col>
                <el-col :xl="12">
                    <el-form-item :label="$t('platform.setting.config.max_award')">
                        <component-page-numeral :num="data.max_award" v-if="data.max_award != null"></component-page-numeral>
                        <component-page-loading status="nodata" v-else></component-page-loading>
                    </el-form-item>
                </el-col>

                <el-col :xl="12">
                    <el-form-item :label="$t('platform.setting.config.game_validity_period')">
                        <component-page-numeral :num="data.game_validity_period" v-if="data.game_validity_period != null"></component-page-numeral>
                        <component-page-loading status="nodata" v-else></component-page-loading>
                    </el-form-item>
                </el-col>

                <el-col :xl="12">
                    <el-form-item :label="$t('platform.setting.config.time_zone')">
                        <div v-if="data.time_zone != null">{{ $t(`platform.setting.config.time_zone_index.${data.time_zone}.label`) }}</div>
                        <component-page-loading status="nodata" v-else></component-page-loading>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-dialog :title="$t('platform.setting.config.dialog.update')" width="560px" :visible.sync="dialog.visible.update">
            <div class="pr-12" style="min-height: 330px">
                <el-form :model="currencyCache" label-width="110px">
                    <el-form-item :label="$t('platform.setting.config.currency_custom.title')"
                                  :error="Boolean(msg.errors['multiple']) ? msg.errors['multiple'][0] : '' ||
                                          Boolean(msg.errors['real_currency']) ? msg.errors['real_currency'][0] : ''">
                        <el-row>
                            <el-col :span="10">
                                <component-page-loading :status="currencyListStatus" @reload="getCurrencyList" v-if="currencyListStatus != 'dle'"></component-page-loading>
                                <el-select :placeholder="$t('platform.setting.config.currency_custom.real_currency')"
                                           class="block" v-model="currencyCache.real_currency" filterable clearable v-else>
                                    <el-option v-for="item in currencyList" :key="item.currency" :label="item.currency" :value="item.currency"></el-option>
                                </el-select>
                            </el-col>
                            <el-col :span="10">
                                <el-input :placeholder="$t('platform.setting.config.currency_custom.multiple')"
                                          type="number" v-model.number="currencyCache.multiple"></el-input>
                            </el-col>
                            <el-col :span="4" class="text-right">
                                <el-button class="px-4" icon="el-icon-plus" @click="customCurrency"></el-button>
                            </el-col>
                        </el-row>
                    </el-form-item>
                </el-form>
                <el-form :model="dataCache" label-width="110px">
                    <el-form-item :label="$t('platform.setting.config.currency')" :error="Boolean(msg.errors['currency']) ? msg.errors['currency'][0] : ''" required>
                        <component-page-option-currency v-model="dataCache.currency" class="block" v-if="!currencyRefresh"></component-page-option-currency>
                    </el-form-item>
                    <el-form-item :label="$t('platform.setting.config.payment')" :error="Boolean(msg.errors['payment']) ? msg.errors['payment'][0] : ''" required>
                        <el-select class="block" v-model="dataCache.payment" :disabled="dataCache.id != null">
                            <el-option v-for="item in $t('platform.setting.config.paymentList')" :key="item.value" :label="item.label" :value="item.value" :disabled="item.value == 2"></el-option>
                        </el-select>
                        <el-alert type="warning" :closable="false" class="leading-normal mt-3 px-1"
                                  v-if="$te(`platform.setting.config.paymentList.${dataCache.payment}`)"
                                  :title="$t(`platform.setting.config.paymentList.${dataCache.payment}.desc`)">
                        </el-alert>
                    </el-form-item>
                    <el-form-item :label="$t('platform.setting.config.rate')" :error="Boolean(msg.errors['rate']) ? msg.errors['rate'][0] : ''">
                        <el-col :span="11">
                            <el-input type="number" v-model.number="dataCache.rate" min="0" max="1" step="0.01"></el-input>
                        </el-col>
                        <el-col :span="2" class="text-center">
                            <i class="el-icon-right"></i>
                        </el-col>
                        <el-col :span="11">
                            <el-input :value="!Boolean(dataCache.rate) ? null : $store.getters['config/filterNumeral'](dataCache.rate * 100)" disabled>
                                <span slot="suffix">%</span>
                            </el-input>
                        </el-col>
                    </el-form-item>
                    <el-form-item :label="$t('platform.setting.config.max_award')" :error="Boolean(msg.errors['max_award']) ? msg.errors['max_award'][0] : ''">
                        <el-input type="number" v-model.number="dataCache.max_award"></el-input>
                    </el-form-item>

                    <el-form-item :label="$t('platform.setting.config.game_validity_period')" :error="Boolean(msg.errors['game_validity_period']) ? msg.errors['game_validity_period'][0] : ''">
                        <el-input type="number" v-model.number="dataCache.game_validity_period"></el-input>
                        <el-alert type="warning" :closable="false" class="leading-normal mt-3 px-1"
                                  :title="$t(`platform.setting.config.game_validity_period_desc`)">
                        </el-alert>
                    </el-form-item>

                    <el-form-item :label="$t('platform.setting.config.time_zone')" :error="Boolean(msg.errors['time_zone']) ? msg.errors['time_zone'][0] : ''">
                        <el-select v-model="dataCache.time_zone" class="block">
                            <el-option v-for="(item,index) in $t('platform.setting.config.time_zone_index')" :key="index" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>


                    <el-form-item>
                        <el-button type="primary" @click="onSubmit">{{ $t('action.confirm') }}</el-button>
                        <el-button @click="dialog.visible.update = false">{{ $t('action.cancel') }}</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: "PlatformConfig",
    props: ['tree'],
    data() {
        return {
            currencyListStatus: 'dle',
            currencyList: [],
            currencyCache: {
                real_currency: '',
                multiple: null,
            },
            currencyInit: {},
            currencyRefresh: false,
            dataStatus: 'dle',
            data: {
                plat_code: null,
                currency: [],
                payment: null,
                rate: null,
                max_award: null,
                game_validity_period: null,
                time_zone: null,
            },
            dataCache: {},
            dataInit: {},
            dialog: {
                visible: {
                    update: false,
                }
            },
            msg: {
                code: 200,
                message: '',
                errors: {},
            },
        }
    },
    watch: {
        tree: {
            deep: true,
            immediate: true,
            handler(n, o) {
                // 获取数据
                n.id != null && this.getData();
            }
        },
    },
    created() {
        // 备份初始数据
        this.currencyInit = _.cloneDeep(this.currencyCache);
        this.dataInit = _.cloneDeep(this.data);
        // 获取币种列表
        this.getCurrencyList();
    },
    methods: {
        // 获取币种列表
        getCurrencyList() {
            this.currencyListStatus = 'loading';
            axios.get('/common/getCurrencyList', {
                params: {system: true}
            }).then((response) => {
                if (response.data.resp_msg.code == 200) {
                    this.currencyList = response.data.resp_data;
                    this.currencyListStatus = 'dle';
                } else {
                    this.currencyListStatus = 'error';
                }
            })
        },
        // 获取数据
        getData() {
            this.dataStatus = 'loading';
            axios.get('/platform/setting/config/getData', {
                params: {
                    plat_code: this.tree.code
                }
            }).then((response) => {
                if (_.includes([200, 44100], response.data.resp_msg.code)) {
                    this.data = response.data.resp_data || _.cloneDeep(this.dataInit);
                    this.dataStatus = 'dle';
                    // 广播事件到父组件
                    this.$emit('update', this.data);
                } else {
                    this.dataStatus = 'error';
                }
            })
        },
        initMsg() {
            this.msg.code = 200;
            this.msg.message = '';
            this.msg.errors = {};
        },
        // 显示模态框（编辑）
        dialogUpdate() {
            this.initMsg();
            // 缓存数据
            this.currencyCache = _.cloneDeep(this.currencyInit);
            this.dataCache = _.cloneDeep(this.data);
            // 平台code
            this.dataCache.plat_code = this.tree.code;
            // 平台税率
            if (Boolean(this.dataCache.rate)) {
                this.dataCache.rate = this.$store.getters['config/filterNumeral'](this.dataCache.rate);
            }
            // 显示模态框
            this.dialog.visible.update = true;
        },
        customCurrency() {
            this.initMsg();
            // loading 状态 start
            let loading = this.$loading();
            // 保存数据
            axios.post('/platform/setting/config/customCurrency', this.currencyCache).then((response) => {
                // loading 状态 close
                loading.close();
                // 逻辑处理
                if (response.data.resp_msg.code == 200) {
                    this.$message({
                        type: 'success',
                        message: this.$t('messages.succeeded', {status: this.$t('action.add')}),
                        showClose: true
                    });
                    // 刷新数据
                    this.currencyRefresh = true;
                    setTimeout(() => {
                        this.currencyRefresh = false;
                    }, 100)
                } else if (response.data.resp_msg.code == 42000) {
                    this.$message({
                        type: 'error',
                        message: response.data.resp_msg.message,
                        showClose: true
                    });
                    this.msg = response.data.resp_msg;
                } else {
                    this.$message({
                        type: 'error',
                        dangerouslyUseHTMLString: true,
                        message: this.$t('messages.failed', {status: this.$t('action.add')}) + `<div class="mt-2">${response.data.resp_msg.message}</div>`,
                        showClose: true
                    });
                }
            })
        },
        onSubmit() {
            this.initMsg();
            // loading 状态 start
            let loading = this.$loading();
            // 保存数据
            axios.post('/platform/setting/config/updateOrCreate', this.dataCache).then((response) => {
                // loading 状态 close
                loading.close();
                // 逻辑处理
                if (response.data.resp_msg.code == 200) {
                    this.$message({
                        type: 'success',
                        message: this.$t('messages.succeeded', {status: this.$t('action.edit')}),
                        showClose: true
                    });
                    // 更新数据
                    this.data = response.data.resp_data;
                    // 关闭模态框
                    this.dialog.visible.update = false;
                    // 广播事件到父组件
                    this.$emit('update', this.data);
                } else if (response.data.resp_msg.code == 42000) {
                    this.$message({
                        type: 'error',
                        message: response.data.resp_msg.message,
                        showClose: true
                    });
                    this.msg = response.data.resp_msg;
                } else {
                    this.$message({
                        type: 'error',
                        dangerouslyUseHTMLString: true,
                        message: this.$t('messages.failed', {status: this.$t('action.edit')}) + `<div class="mt-2">${response.data.resp_msg.message}</div>`,
                        showClose: true
                    });
                }
            })
        },
    }
}
</script>

<style scoped>

</style>
